package com.szis.auth.runner;

import com.szis.auth.common.ServerManager;
import com.szis.auth.common.utils.CustomSnowflakeIdGenerator;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * ID生成器
 * @author: yxl
 * 2025-07-18
 */

@Component
@Order(3)
public class IdGenerator implements CommandLineRunner {

    @Value("${spring.application.name}")
    private String appName;
    @Resource
    private ServerManager serverManager;
    private CustomSnowflakeIdGenerator idGenerator;

    @Override
    public void run(String... args) {
        int serviceId = appName.hashCode() & 0x3FF;
        int nodeId = serverManager.workerId(appName, serverManager.get());
        idGenerator = new CustomSnowflakeIdGenerator(serviceId, nodeId);
    }

    /**
     * 生成ID
     * @return ID
     */
    public long nextId() {
        return idGenerator.nextId();
    }

    /**
     * 解析ID
     * @param id id
     */
    public static void parseId(long id) {
        CustomSnowflakeIdGenerator.parseId(id);
    }

}
